import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import cookie from "js-cookie"

//跨域请求
axios.defaults.withCredentials = true
//请求头
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
//请求地址
axios.defaults.baseURL="http://localhost:9002"
//请求时间
axios.defaults.timeout=5000


//请求拦截
axios.interceptors.request.use(request=>{
  if(cookie.get("get_token")){
    request.headers["token"] = cookie.get("get_token")
  }
  return request;
},
err=>{
  return Promise.reject(err)
}
)


axios.interceptors.response.use(response=>{
//这个是请求成功
 const res = response.data
   if (res.code !== 200) {

     Message({
       message: res.message,
       type: 'error',
       duration: 5 * 1000
     })
     return Promise.reject('error')
  }else {
    return response.data
  }

},
//这个是请求失败
error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }

)

export function get(URL,params={}){
	return new Promise((resolve,reject)=>{
		axios.get(URL,{params:params})
		.then(res=>{
			resolve(res)
		})
		.catch(err=>{
			reject(err)
		})
	})
}

export function del(URL,params={}){
	return new Promise((resolve,reject)=>{
		axios.delete(URL,{params:params})
		.then(res=>{
			resolve(res)
		})
		.catch(err=>{
			reject(err)
		})
	})
}
export function put(URL,data){
	return new Promise((resolve,reject)=>{
		axios.put(URL,data)
		.then(res=>{
			resolve(res)
		})
		.catch(err=>{
			reject(err)
		})
	})
}
export function post(url, params) {
    return new Promise((resolve, reject) => {
         axios.post(url,params)
        .then(res => {
            resolve(res);
        })
        .catch(err =>{
            reject(err)
        })
    });
}
